package com.meixiang.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.homes.shopping.VerifyGoodsOrderActivity;
import com.meixiang.adapter.shopping.GoodsSpecAdapter;
import com.meixiang.entity.shopping.SpecTagEntity;
import com.meixiang.entity.shopping.SpecTagGoodsEntity;
import com.meixiang.entity.shopping.result.BalanceAccountResult;
import com.meixiang.entity.shopping.result.SpecTagResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.GoodsNumChangeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品购买Dialog
 *
 * @author LZRUI
 */
public class BuyGoodsDialogFragment extends BaseDialogFragment implements GoodsNumChangeView.GetCurrentNumListener, GoodsSpecAdapter.TagSelectListener {

    public final static String TAG = "BuyGoodsDialogFragment";
    private final static String IS_ADD_TO_CART = "isAddToCart";
    private final static String GOODS_ID = "goodsId";
    private final static String LAST_SELECTED_MAP = "lastSelectedMap";
    private final static String BUY_NUM = "butNum";

    @Bind(R.id.iv_goods_logo)
    ImageView ivGoodsLogo;
    @Bind(R.id.tv_goods_name)
    TextView tvGoodsName;
    @Bind(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @Bind(R.id.tv_stock)
    TextView tvStock;
    @Bind(R.id.goods_num)
    GoodsNumChangeView goodsNum;
    @Bind(R.id.ry_spec)
    RecyclerView rySpec;

    private int buyNum;
    private GoodsSpecAdapter adapter;
    private String Url;
    private boolean isAddToCart; // 是否是添加购物车的操作
    private SpecTagResult tagResult; // 接口返回值
    private Map<Integer, Integer> selectedTagMap = new HashMap<>();  // 缓存用户选择的规格
    private HashMap<Integer, Set<Integer>> lastSelectedMap = new HashMap<>(); // 传给Adapter的缓存规格列表
    private String goodsId; // 商品id

    private CacheListener mCacheListener;
    private LoadingDialog loadingDialog;

    public interface CacheListener {
        /**
         * 缓存选中的标签
         *
         * @param map 列表
         */
        void cacheSelected(HashMap<Integer, Set<Integer>> map);

        /**
         * 缓存购买数量
         *
         * @param num 数量
         */
        void cacheBuyGoodsNum(int num);
    }

    /**
     * 设置缓存事件
     *
     * @param listener 事件
     * @return BuyGoodsDialogFragment
     */
    public BuyGoodsDialogFragment setCacheListener(CacheListener listener) {
        this.mCacheListener = listener;
        return this;
    }

    public static BuyGoodsDialogFragment newInStance(boolean isAddToCart, String goodsId, HashMap<Integer, Set<Integer>> lastSelectedMap, int buyNum) {
        BuyGoodsDialogFragment dialogFragment = new BuyGoodsDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_ADD_TO_CART, isAddToCart);
        bundle.putString(GOODS_ID, goodsId);
        bundle.putSerializable(LAST_SELECTED_MAP, lastSelectedMap);
        bundle.putInt(BUY_NUM, buyNum);
        dialogFragment.setArguments(bundle);
        return dialogFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            isAddToCart = bundle.getBoolean(IS_ADD_TO_CART);
            goodsId = bundle.getString(GOODS_ID);
            if (bundle.getSerializable(LAST_SELECTED_MAP) != null) {
                lastSelectedMap = (HashMap<Integer, Set<Integer>>) bundle.getSerializable(LAST_SELECTED_MAP);
            }
            buyNum = bundle.getInt(BUY_NUM);
        }
    }

    @Override
    protected int setFragmentViewId() {
        return R.layout.dialog_buy_goods;
    }

    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);
        rySpec.setLayoutManager(new LinearLayoutManager(mActivity));
        rySpec.setAdapter(adapter = new GoodsSpecAdapter());
        goodsNum.setGetCurrentNumListener(this);
        goodsNum.initNum(buyNum);
    }

    @Override
    protected void initData() {
        specSearch(null);
        adapter.setTagSelectListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    @OnClick({R.id.imgBtn_delete, R.id.tv_sure})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            case R.id.imgBtn_delete:
                dismiss();
                break;
            case R.id.tv_sure:
                submit();
                break;
        }
    }

    @Override
    public void getCurrentNum(int currentNum) {
        buyNum = currentNum;
        if (mCacheListener != null) {
            mCacheListener.cacheBuyGoodsNum(currentNum);
        }
    }

    @Override
    public void onSelected(int specPosition, Set<Integer> selectPosSet) {
        if (selectPosSet.size() == 0) {
            if (lastSelectedMap != null) {
                lastSelectedMap.remove(specPosition);
            }
        } else {
            if (lastSelectedMap != null) {
                lastSelectedMap.put(specPosition, selectPosSet);
            }
        }
        if (mCacheListener != null) {
            // 将选中的tag回调给activity，方便下次进入显示
            mCacheListener.cacheSelected(lastSelectedMap);
        }
        // 由于tag是单选，所以始终只有一个tag
        Iterator<Integer> iterator = selectPosSet.iterator();
        if (iterator.hasNext()) {
            selectedTagMap.put(specPosition, iterator.next());
        } else {
            selectedTagMap.remove(specPosition);
        }
        specSearch(getSValueIds());
    }

    /**
     * 按规格查询商品
     */
    private void specSearch(String spValueIds) {
        HttpParams params = new HttpParams();
        params.put("spValueIds", spValueIds);
        params.put("goodsId", goodsId);

        Log.i("lzrtest", "按规格查询商品   " + params.toString());

        HttpUtils.post(Config.GOODS_SPEC_SELECT, TAG, params, new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                tagResult = AbJsonUtil.fromJson(result.toString(), SpecTagResult.class);
                if (tagResult != null && adapter != null) {
                    adapter.refreshData(tagResult, lastSelectedMap);
                    if (tagResult.getGoods() != null && mActivity != null) {
                        SpecTagGoodsEntity goods = tagResult.getGoods();
                        tvStock.setText(String.format(mActivity.getString(R.string.stock_num), goods.getGoodsStorage()));
                        goodsNum.setMaxNum(Integer.valueOf(goods.getGoodsStorage().trim()));
                        GlideHelper.showImage(mActivity, goods.getGoodsImage(), R.drawable.image_default_white_bg, ivGoodsLogo);
                        tvGoodsPrice.setText(String.format(mActivity.getString(R.string.price_str), goods.getGoodsStorePrice()));
                        tvGoodsName.setText(goods.getGoodsName());
                    }
                }
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
            }

        });
    }

    /**
     * 加入购物车、购买
     * </p>
     * 直接购买也先走购物车流程
     */
    private void submit() {
        // 没有选择全部的标签
        if (!isSelectedAllTag()) return;
        HttpParams params = new HttpParams();
        SpecTagGoodsEntity goods = tagResult.getGoods();
        params.put("storeId", tagResult.getStoreId());
        params.put("spValueIds", getSValueIds());
        params.put("goodsStorePrice", goods.getGoodsStorePrice());
        params.put("goodsId", goodsId);
        params.put("goodsNum", String.valueOf(buyNum));

        Log.i("lzrtest", "加入购物车： " + params.toString());
        if(isAddToCart){
            //加入购物车地址
            Url= Config.ADD_TO_CART;
        }else{
            //加直接购买
            Url= Config.GOODS_CART_BUY;
        }
        HttpUtils.post(Url, params, new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (lastSelectedMap != null && mCacheListener != null) {
                    lastSelectedMap.clear();
                    mCacheListener.cacheSelected(lastSelectedMap);
                }
                if (mCacheListener != null) {
                    mCacheListener.cacheBuyGoodsNum(1);
                }
                if (isAddToCart) {
                    // 加入购物车
                    Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
                } else {
                    // 直接购买
                    try {
                        createOrder(result.getString("cartId"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dismiss();
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 生成订单，进入确认订单界面
     */
    private void createOrder(String cartId) {
        HttpUtils.post(Config.BALANCE_ACCOUNT, new HttpParams("cartIds", cartId), new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                BalanceAccountResult balanceAccountResult = AbJsonUtil.fromJson(result.toString(), BalanceAccountResult.class);
                Intent intent = new Intent(mActivity, VerifyGoodsOrderActivity.class);
                intent.putExtra(VerifyGoodsOrderActivity.ORDER_DATA, balanceAccountResult);
                mActivity.startActivity(intent);
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getSValueIds() {
        if (tagResult == null) return "";
        StringBuilder sValueIds = new StringBuilder();
        // 获得所有标签种类的数量
        int specLen = tagResult.getSpecList().size();
        for (int i = 0; i < specLen; i++) {
            if (selectedTagMap.get(i) != null) {
                int specValuePos = selectedTagMap.get(i);
                // 获取到对应的标签种类
                SpecTagEntity tag = tagResult.getSpecList().get(i);
                // 获取对应种类的值对应的value
                String specValueId = tag.getSpecValueList().get(specValuePos).getSpValueId();
                sValueIds.append(specValueId);
                sValueIds.append(";");
            }
        }
        return sValueIds.toString().equals("") ? null : sValueIds.toString();
    }

    /**
     * 判断是否选择了全部标签
     */
    private boolean isSelectedAllTag() {
        if (tagResult == null) return false;
        int specLen = tagResult.getSpecList().size();
        if (lastSelectedMap != null && lastSelectedMap.size() < specLen) {
            StringBuilder message = new StringBuilder("请选择  ");
            for (int i = 0; i < specLen; i++) {
                if (lastSelectedMap.get(i) == null || !lastSelectedMap.get(i).iterator().hasNext()) {
                    SpecTagEntity tagEntity = tagResult.getSpecList().get(i);
                    message.append(tagEntity.getSpName());
                    message.append(" ");
                }
            }
            Toast.makeText(mActivity, message.toString(), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

}
